package cz.cernilovsky.android.profileapp.activities;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import cz.cernilovsky.android.profileapp.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;

public class MapActivity extends FragmentActivity {
	private GoogleMap map;
	public static final int OK = 1;
	public static final int CANCEL = 2;
	public static final String LATITUDE = "latitude";
	public static final String LONGITUDE = "longitude";
	private double latitude;
	private double longitude;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		setResult(CANCEL);
		if(savedInstanceState != null) {
			latitude = savedInstanceState.getDouble(LATITUDE);
			longitude = savedInstanceState.getDouble(LONGITUDE);
			moveAndMark();
		} else {
			Bundle extras = getIntent().getExtras();
			if(extras != null) {
				latitude = extras.getDouble(LATITUDE);
				longitude = extras.getDouble(LONGITUDE);
				moveAndMark();
			}
		}
	}
	
	private void moveAndMark() {
		if(map == null) {
			map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
			map.setOnMapClickListener(new ClickListener());
			map.setMyLocationEnabled(true);
		}
		LatLng pos = new LatLng(latitude, longitude);
		CameraPosition camPos = new CameraPosition.Builder().target(pos).zoom(5).build();
		map.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
		MarkerOptions options = new MarkerOptions();
		options.position(pos);
		map.clear();
		map.addMarker(options);
	}

	public void save(View view) {
		Intent data = new Intent();
		data.putExtra(LATITUDE, latitude);
		data.putExtra(LONGITUDE, longitude);
		setResult(OK, data);
		finish();
	}

	class ClickListener implements GoogleMap.OnMapClickListener {

		@Override
		public void onMapClick(LatLng pos) {
			latitude = pos.latitude;
			longitude = pos.longitude;
			MarkerOptions options = new MarkerOptions();
			options.position(pos);
			map.clear();
			map.addMarker(options);
		}
		
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putDouble(LATITUDE, latitude);
		outState.putDouble(LONGITUDE, longitude);
	}
	

}
